/*
 * Copyright (c) 2023 Beijing HuaQing YuanJian Education Technology Co., Ltd
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

 #include <stdio.h>
 #include <unistd.h>
 #include <string.h>
 #include "ohos_init.h"
 #include "cmsis_os2.h"
 #include "hal_bsp_sht20.h"
 #include "hal_bsp_pcf8574.h"
 #include "hal_bsp_ssd1306.h"
 
 osThreadId_t Task1_ID; // 任务1设置为低优先级任务
 #define TASK_STACK_SIZE 1024
 
 // 温湿度获取并显示到OLED
 void oled_task(void)
 {
     float temperature = 0, humidity = 0;
     uint8_t displayBuff[20] = {0};
 
     // OLED 显示屏初始化
     SSD1306_Init();
     SSD1306_CLS(); // 清屏
 
     // 显示标题
     //SSD1306_ShowStr(0, 0, (uint8_t *)"  Temp & Humidity  ", 16);
 
     while (1) {
         // 获取温湿度
         SHT20_ReadData(&temperature, &humidity);
 
         // 清空显示缓冲区
         memset(displayBuff, 0, sizeof(displayBuff));
         
         // 将温湿度数据显示到OLED
         sprintf((char *)displayBuff, "Temp: %.2f C", temperature);
         SSD1306_ShowStr(0, 2, displayBuff, 16); // 显示温度
 
         memset(displayBuff, 0, sizeof(displayBuff)); // 清空缓冲区
         sprintf((char *)displayBuff, "Hum: %.2f %%", humidity);
         SSD1306_ShowStr(0, 3, displayBuff, 16); // 显示湿度
 
         sleep(1); // 每秒更新一次数据
     }
 }
 
 static void oled_i2c(void)
 {
     osThreadAttr_t options;
     options.name = "oled_task";
     options.attr_bits = 0;
     options.cb_mem = NULL;
     options.cb_size = 0;
     options.stack_mem = NULL;
     options.stack_size = 1024;
     options.priority = osPriorityNormal;
 
     Task1_ID = osThreadNew((osThreadFunc_t)oled_task, NULL, &options);
     if (Task1_ID != NULL) {
         printf("ID = %d, Create Task1_ID is OK!\r\n", Task1_ID);
     }
 }
 
 static void base_sht20_demo(void)
 {
     printf("Enter base_sht20_demo()!\n");
 
     PCF8574_Init();
     SHT20_Init(); // SHT20初始化
 
     oled_i2c(); // 启动OLED显示
 }
 
 SYS_RUN(base_sht20_demo);
 